package org.itec.yeast.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.itec.yeast.trdo.TRCorrelation;
import org.itec.yeast.trdo.TRCorrelationSQL;
import org.itec.yeast.trdo.TRStrainSQL;
import org.itec.yeast.trdo.TRYeastGeneSQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CorrelationFetcher {
	private static final Logger log = LoggerFactory.getLogger(CorrelationFetcher.class);
	private static final int STORE_NUM_MAX = 1000;
	private static final String FIELD_SEPARATER = "\t";
	private static final int FIELD_NUMBER = 3;
	private static final int STRAIN_MARKER_TYPE_Q = 0;
	private static final int STRAIN_MARKER_TYPE_A = 1;
	private String PREFIX_PATH = "";
	private String ARRAY_DATA_FILEPATH = "";
	private String QUERY_DATA_FILEPATH = "";

	private List<TRCorrelation> correlations = new ArrayList<TRCorrelation>();

	public CorrelationFetcher() throws URISyntaxException {
		super();
		String fullPath = DataFetcher.class.getClassLoader().getResource("").toURI().getPath();
		PREFIX_PATH = fullPath.substring(0, fullPath.indexOf("WEB-INF/classes") - 1);
		ResourceBundle bundle = ResourceBundle.getBundle("yeast");
		ARRAY_DATA_FILEPATH = bundle.getString("CORRELATION_ARRAY");
		QUERY_DATA_FILEPATH = bundle.getString("CORRELATION_QUERY");
		if (QUERY_DATA_FILEPATH.equals("") || ARRAY_DATA_FILEPATH.equals("") || PREFIX_PATH.equals("")) {
			log.error("Correlation数据信息配置错误，请检查yeast.properties文件!");
			return;
		}
	}

	public void getCorrelationData() {
		BufferedReader reader = null;
		TRYeastGeneSQL yeastGeneSQL = new TRYeastGeneSQL();
		Map<String, Integer> geneIDs = yeastGeneSQL.getGeneIDs();
		TRCorrelationSQL correlationSQL = new TRCorrelationSQL();

		// Get array correlation data
//		try {
//			reader = new BufferedReader(
//						new InputStreamReader(
//						new FileInputStream(
//						new File(PREFIX_PATH + ARRAY_DATA_FILEPATH))));
//			String line = null;
//
//			while ((line = reader.readLine()) != null) {
//				storeCorrelation(line, strainIDs, STRAIN_MARKER_TYPE_A);
//			}
//			if (correlations.size() > 0) {
//				correlationSQL.insert(correlations);
//				correlations.clear();
//			}
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			log.error("文件" + PREFIX_PATH + ARRAY_DATA_FILEPATH + "未找到");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			log.error("读取文件" + ARRAY_DATA_FILEPATH + "失败!");
//		} finally {
//			if (reader != null) {
//				try {
//					reader.close();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
		
		// Get query correlation data
		try {
			reader = new BufferedReader(
						new InputStreamReader(
						new FileInputStream(
						new File(PREFIX_PATH + QUERY_DATA_FILEPATH))));
			String line = null;

			while ((line = reader.readLine()) != null) {
				storeCorrelation(line, geneIDs, STRAIN_MARKER_TYPE_Q);
			}
			if (correlations.size() > 0) {
				correlationSQL.insert(correlations);
				correlations.clear();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("文件" + PREFIX_PATH + QUERY_DATA_FILEPATH + "未找到");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("读取文件" + QUERY_DATA_FILEPATH + "失败!");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private void storeCorrelation(String line, Map<String, Integer> geneIDs, int type) {
		String[] contents = line.split(CorrelationFetcher.FIELD_SEPARATER);
		if (contents.length != CorrelationFetcher.FIELD_NUMBER) {
			log.error("Correlation数据格式错误。本行内容" + line);
			return;
		}
		
		String qStrain = "";
		String aStrain = "";
		String condition = "";
		if (contents[0].contains("_")) {
			qStrain = contents[0].substring(0, contents[0].indexOf("_"));
			condition = contents[0].substring(contents[0].indexOf("_") + 1, contents[0].length());
		} else {
			qStrain = contents[0];
		}

		if (contents[1].contains("_")) {
			aStrain = contents[1].substring(0, contents[1].indexOf("_"));
			if (condition.length() != 0){
				condition += "|" + contents[1].substring(contents[1].indexOf("_") + 1, contents[1].length());
			} else {
				condition += contents[1].substring(contents[1].indexOf("_") + 1, contents[1].length());
			}
		} else {
			aStrain = contents[1];
		}

		double score = Double.parseDouble(contents[2].substring(1, contents[2].length()));

		int qStrainID = -1;
		int aStrainID = -1;
		if (geneIDs.containsKey(qStrain)) {
			qStrainID = geneIDs.get(qStrain);
		}
		if (geneIDs.containsKey(aStrain)) {
			aStrainID = geneIDs.get(aStrain);
		}
		
		if (qStrainID == -1 || aStrainID == -1){
			return;
		}
		
		TRCorrelation correlation = new TRCorrelation(qStrainID, aStrainID);
		correlation.setScore(score);
		correlation.setType(type);
		correlation.setCondition(condition);
		correlations.add(correlation);
		if (correlations.size() >= (10 * CorrelationFetcher.STORE_NUM_MAX)) {
			TRCorrelationSQL correlationSQL = new TRCorrelationSQL();
			correlationSQL.insert(correlations);
			correlations.clear();
		}

	}
	
	public static void main(String[] args) throws URISyntaxException{
		CorrelationFetcher fetcher = new CorrelationFetcher();
		fetcher.getCorrelationData();
	}
}
